<template>
  <div class="ele-body">
    <!-- 搜索表单 -->
    <div class="block-interval">
      <a-card :bordered="false">
        <a-form layout="inline" :model="where">
          <a-row>
            <a-form-item label="开始时间:">
              <a-date-picker v-model:value="where.searchBeginTime" type="date" show-time format="YYYY-MM-DD HH:mm:ss" valueFormat="YYYY-MM-DD HH:mm:ss" />
            </a-form-item>
            <a-form-item label="结束时间:">
              <a-date-picker v-model:value="where.searchEndTime" type="date" show-time format="YYYY-MM-DD HH:mm:ss" valueFormat="YYYY-MM-DD HH:mm:ss" />
            </a-form-item>
            <a-form-item class="ele-text-center">
              <a-space>
                <a-button type="primary" @click="reload">查询</a-button>
                <a-button @click="reset">重置</a-button>
              </a-space>
            </a-form-item>
          </a-row>
        </a-form>
      </a-card>
    </div>

    <!-- 表格 -->
    <div>
      <a-card :bordered="false">
        <ele-pro-table
          ref="table"
          row-key="scsclId"
          :datasource="datasource"
          :columns="columns"
          :where="where"
          :scroll="{ x: 'max-content' }"
        >
          <template #bodyCell="{ column, record }">
            <!-- table操作栏按钮 -->
            <template v-if="column.key === 'action'">
              <a-space>
                <a-popconfirm title="确定要删除此记录吗？" @confirm="remove(record)">
                  <a class="ele-text-danger">删除</a>
                </a-popconfirm>
                <a-divider type="vertical" />
                <a @click="openTimeTempManageDialog(record)">温度模式调度数据</a>
              </a-space>
            </template>
          </template>
        </ele-pro-table>
      </a-card>
    </div>

    <!-- JSON查看弹窗 -->
    <a-modal
      v-model:visible="jsonModalVisible"
      :title="jsonModalTitle"
      width="1000px"
      :footer="null"
    >
      <a-card :bordered="false">
        <template v-if="jsonModalTitle === '分配结果'">
          <a-collapse v-model:activeKey="activeKeys">
            <a-collapse-panel v-for="(item, index) in jsonData" :key="index" :header="`时间段 ${index + 1}  (${item.start} - ${item.end})`">
              <a-descriptions bordered>
                <a-descriptions-item label="时间段序号" :span="3">
                  {{ item.index }}/16
                </a-descriptions-item>
                <a-descriptions-item label="时间范围" :span="3">
                  {{ item.start }} - {{ item.end }}
                </a-descriptions-item>
                <a-descriptions-item label="分区" :span="3">
                  {{ item.region }}
                </a-descriptions-item>
                <a-descriptions-item label="使用组别" :span="3">
                  {{ getValidText(item.valid) }}
                </a-descriptions-item>
                <a-descriptions-item label="喷淋模式" :span="3">
                  {{ getModeText(item.mode) }}
                </a-descriptions-item>
                <a-descriptions-item label="忽略算法" :span="3">
                  {{ getAlgText(item.alg) }}
                </a-descriptions-item>
                <a-descriptions-item label="喷淋/停止时长" :span="3" v-if="item.valid !== 8 && item.valid !== 7">
                  喷淋: {{ item.time_action_stop.action }}秒,
                  停止: {{ item.time_action_stop.stop }}秒
                </a-descriptions-item>
              </a-descriptions>

              <div v-if="item.valid !== 8 && item.valid !== 7">
                <div class="time-strategy-title">分区时间段划分：</div>
                <div v-for="(times, region) in item.time_strategy" :key="region" class="time-strategy-item">
                  <div class="region-title">分区 {{ region }}:</div>
                  <a-collapse v-model:activeKey="timeActiveKeys">
                    <a-collapse-panel 
                        :key="region" 
                        :header="getTimeStrategyHeader(times, region, item.time_slot_version)"
                    >
                      <a-table
                        :dataSource="formatTimeStrategy(times)"
                        :columns="timeStrategyColumns"
                        size="small"
                        :pagination="false"
                      />
                    </a-collapse-panel>
                  </a-collapse>
                </div>

                <div class="time-strategy-title">分区时间点划分：</div>
                <div v-for="(times, region) in item.dahua_time_strategy" :key="region" class="time-strategy-item">
                  <div class="region-title">分区 {{ region }}:</div>
                  <a-collapse v-model:activeKey="dahuaTimeActiveKeys">
                    <a-collapse-panel 
                        :key="region" 
                        :header="getTimeStrategyHeader(times, region, item.time_slot_version)"
                    >
                      <a-table
                        :dataSource="formatDahuaTimeStrategy(times)"
                        :columns="dahuatTimeStrategyColumns"
                        size="small"
                        :pagination="false"
                      />
                    </a-collapse-panel>
                  </a-collapse>
                </div>
              </div>
            </a-collapse-panel>
          </a-collapse>
        </template>
        <template v-else>
          <pre class="json-viewer">{{ formatJson(jsonData) }}</pre>
        </template>
      </a-card>
    </a-modal>

    <DeviceManagerdeviceCameraGroupmanagerTimerangeTemprange v-if="showTimerTemp" v-model:visible="showTimerTemp" :data="current" @done="reload" />
  </div>
</template>

<script>
import { h } from 'vue';
import { DeviceSprayCameraScheduleConfigLogApi } from "@/api/property/spraycamera/DeviceSprayCameraScheduleConfigLogApi";
import { message } from 'ant-design-vue';
import DeviceManagerdeviceCameraGroupmanagerTimerangeTemprange from './camera-groupmanager-timerangetemprange.vue'
export default {
  name: 'DeviceManagerdeviceCameraGroupmanagerScheduleconfigLog',
  components: {
    DeviceManagerdeviceCameraGroupmanagerTimerangeTemprange
  },
  props: {
    data: Object
  },
  data() {
    return {
      // 表格列配置
      columns: [
        {
          title: '记录id',
          dataIndex: 'scsclId'
        },
        {
          title: '创建时间',
          dataIndex: 'createTime'
        },
        {
          title: '是否生效',
          dataIndex: 'effect',
          customRender: ({ text }) => {
            return text ? '生效中' : '未生效';
          }
        },
        {
          title: '识别容忍度(秒)',
          dataIndex: 'idendify',
          width: 80
        },
        {
          title: '喷淋模式',
          dataIndex: 'sprayModelData',
          ellipsis: true,
          customRender: ({ text }) => {
            return h('a', {
              onClick: () => this.viewJsonData('喷淋模式', text)
            }, text ? '查看详情' : '-');
          }
        },
        {
          title: '时间段设置',
          dataIndex: 'timeModelConf',
          ellipsis: true,
          customRender: ({ text }) => {
            return h('a', {
              onClick: () => this.viewJsonData('时间段设置', text)
            }, text ? '查看详情' : '-');
          }
        },
        {
          title: '温控设置',
          dataIndex: 'tempModelConf',
          ellipsis: true,
          customRender: ({ text }) => {
            return h('a', {
              onClick: () => this.viewJsonData('温控设置', text)
            }, text ? '查看详情' : '-');
          }
        },
        {
          title: '分配结果',
          dataIndex: 'timeModeResult',
          ellipsis: true,
          customRender: ({ text }) => {
            return h('a', {
              onClick: () => this.viewJsonData('分配结果', text)
            }, text ? '查看详情' : '-');
          }
        },
        {
          title: '分配状态',
          dataIndex: 'status',
          customRender: function(row) {
            if (row.text == 2) {
              return "分配成功";
            } else if (row.text == 3) {
              return "分配失败";
            } else {
              return "未分配";
            }
          }
        },
        {
          title: '失败原因',
          dataIndex: 'msg'
        },
        {
          title: '操作',
          key: 'action',
          width: 280,
          align: 'center'
        }
      ],
      // 表格搜索条件
      where: {
        oxtallId : this.data.oxtallId
      },
      // 表格选中数据
      selection: [],
      // 当前编辑数据
      current: null,
      // 是否显示编辑弹窗
      showEdit: false,
      jsonModalTitle : '',
      jsonModalVisible : false,
      jsonData : {},
      timeStrategyColumns: [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
        },
        {
          title: '开始时间',
          dataIndex: 'start',
          width: 150,
        },
        {
          title: '结束时间',
          dataIndex: 'end',
          width: 150,
        },
        {
          title: '时长',
          dataIndex: 'duration',
        }
      ],
      dahuatTimeStrategyColumns: [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
        },
        {
          title: '开始时间',
          dataIndex: 'start',
          width: 150,
        },
        {
          title: '执行时长',
          dataIndex: 'runduration',
          width: 150,
        },
        {
          title: '等待时长',
          dataIndex: 'waitduration',
        }
      ],
      activeKeys: [], // 控制折叠面板的展开状态
      timeActiveKeys: [], // 控制时间段表格的展开状态
      dahuaTimeActiveKeys : [],
      showTimerTemp : false
    };
  },
  methods: {
    getTimeStrategyHeader(times, region, versionInfo) {
      let header = `时间段列表（${times.length}个）`;
      if (versionInfo && versionInfo[region]) {
        header += ` - 版本号：${versionInfo[region]}`;
      }
      return header;
    },
    /**
     * 搜索按钮
     *
     * @author cancan
     * @date 2025/03/22 22:16
     */
    reload() {
      this.selection = [];
      this.$refs.table.reload({ page: 1 });
    },

    /**
     * 重置搜索
     *
     * @author cancan
     * @date 2025/03/22 22:16
     */
    reset() {
      this.oxtallId = this.data.oxtallId;
      this.where.searchBeginTime = '';
      this.where.searchEndTime = '';
      this.$nextTick(() => {
        this.reload();
      });
    },

    /**
     * 删除
     *
     * @author cancan
     * @date 2025/03/22 22:16
     */
    async remove(row) {
      const result = await DeviceSprayCameraScheduleConfigLogApi.delete({ scsclId: row.scsclId });
      message.success(result.message);
      this.reload();
    },

    /**
     * 打开新增或编辑弹窗
     *
     * @author cancan
     * @date 2025/03/22 22:16
     */
    openEdit(row) {
      this.current = row;
      this.showEdit = true;
    },
    datasource({ page, limit, where, orders }) {
      return DeviceSprayCameraScheduleConfigLogApi.findPage({ ...where, ...orders, pageNo: page, pageSize: limit });
    },
    viewJsonData(title, jsonStr) {
      this.jsonModalTitle = title;
      try {
        this.jsonData = JSON.parse(jsonStr || '{}');
      } catch (e) {
        this.jsonData = jsonStr || '';
      }
      this.jsonModalVisible = true;
    },

    formatJson(json) {
      try {
        return JSON.stringify(json, null, 2);
      } catch (e) {
        return json;
      }
    },
    getModeText(mode) {
      const modes = {
        1: '所选的区在时间内全开或者全关',
        2: '所选的区,在时间内进行轮流',
        3: '经典喷淋(无时间切片)'
      };
      return modes[mode] || mode;
    },

    getAlgText(alg) {
      const algs = {
        1: '忽略算法',
        2: '不忽略算法'
      };
      return algs[alg] || alg;
    },

    formatTimeStrategy(times) {
      return times.map((time, index) => ({
        key: index,
        index: index + 1,
        start: time[0],
        end: time[1],
        duration: this.calculateDuration(time[0], time[1])
      }));
    },

    formatDahuaTimeStrategy(times) {
      return times.map((time, index) => ({
        key: index,
        index: index + 1,
        start: time[0],
        runduration: `${time[1]}秒`,
        waitduration: `${time[2]}秒`,
      }));
    },

    calculateDuration(start, end) {
      const startParts = start.split(':').map(Number);
      const endParts = end.split(':').map(Number);
      const startSeconds = startParts[0] * 3600 + startParts[1] * 60 + startParts[2];
      const endSeconds = endParts[0] * 3600 + endParts[1] * 60 + endParts[2];
      const durationSeconds = endSeconds - startSeconds;
      return `${durationSeconds}秒`;
    },
    getValidText(valid) {
      if (valid === 0) return '无效';
      if (valid === 7) return '温控模式';
      if (valid === 8) return '不喷水时间段';
      return `时间段模式（${valid}组）`;
    },
    openTimeTempManageDialog(row) {
      this.current = row;
      this.showTimerTemp = true;
    },
  }
};
</script>

<style scoped>
.json-viewer {
  background-color: #f5f5f5;
  padding: 16px;
  border-radius: 4px;
  max-height: 500px;
  overflow: auto;
  font-family: 'Courier New', Courier, monospace;
  white-space: pre-wrap;
  word-break: break-all;
}

.time-strategy-title {
  font-size: 16px;
  font-weight: bold;
  margin: 20px 0 10px;
}

.time-strategy-item {
  margin-bottom: 20px;
}

.region-title {
  font-weight: bold;
  margin-bottom: 10px;
}

:deep(.ant-descriptions) {
  margin-bottom: 20px;
}

:deep(.ant-descriptions-item-label) {
  width: 120px;
}

:deep(.ant-collapse) {
  background: #ffffff;
}

:deep(.ant-collapse-header) {
  font-weight: bold;
  color: #1890ff !important;
}

:deep(.ant-collapse .ant-collapse-header) {
  font-size: 14px;
  color: #666 !important;
  font-weight: normal;
}
</style>
